package com.atguigu.juc;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

public class TestForkJoinPool {

    public static void main(String[] args) {
        ForkJoinPool pool = new ForkJoinPool();

        Instant start = Instant.now();

        ForkJoinTask<Long> task = new ForkJoinSumCalculate(0L, 100000000L);
        Long sum = pool.invoke(task);
        System.out.println(sum);

        Instant end = Instant.now();

        System.out.println("耗时毫秒：" + Duration.between(start,end).toMillis());
    }
}



class ForkJoinSumCalculate extends RecursiveTask<Long> {

    private Long start;
    private long end;

    private static final long THURSHOLD = 10000L;// 临界值

    public ForkJoinSumCalculate(Long start, long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        long length = end - start;
        if (length < THURSHOLD) {
            long sum = 0L;
            for (long i = start; i <=  end ; i++) {
                sum += i;
            }
            return sum;
        }else{
            long middle = (start + end) / 2;
            ForkJoinSumCalculate left = new ForkJoinSumCalculate(start, middle);
            left.fork(); // 进行拆分，并压入到线程队列

            ForkJoinSumCalculate right = new ForkJoinSumCalculate(middle + 1, end);
            right.fork();

            return left.join() + right.join();
        }
    }
}
